import requests
import json
from jsonpath import jsonpath
from openpyxl import workbook
import time

url = 'https://push2.eastmoney.com/api/qt/clist/get?np=1&fltt=1&invt=2&cb=jQuery37102644282991261203_1762590306665&fs=m%3A1%2Bt%3A2%2Bf%3A!2%2Cm%3A1%2Bt%3A23%2Bf%3A!2&fields=f12%2Cf13%2Cf14%2Cf1%2Cf2%2Cf4%2Cf3%2Cf152%2Cf5%2Cf6%2Cf7%2Cf15%2Cf18%2Cf16%2Cf17%2Cf10%2Cf8%2Cf9%2Cf23&fid=f3&pn=1&pz=20&po=1&dect=1&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=%7C0%7C0%7C0%7Cweb'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
}
# 发送请求获取数据
response = requests.get(url, headers=headers)
json_str = response.text
# 去掉开头的字符串"jQuery37102644282991261203_1762590306665(" 和结尾的");"
json_str = json_str[json_str.find('(') + 1:-2]
json_data = json.loads(json_str)
lists = jsonpath(json_data, '$.data.diff[*]')
if not lists:
    print('没有数据')
    exit()
# 创建工作簿
wb = workbook.Workbook()
sh = wb.active
# 写入表头
sh.append(['名称', '代码', '涨幅%'])

for item in lists:
    name = item.get('f14')
    code = item.get('f12')
    zf = str(item.get('f2') / 100) + '%'
    sh.append([name, code, zf])

time = time.strftime('%Y%m%d', time.localtime())
filename = '上证A股票' + time + '.xlsx'
# 保存工作薄为Excel文件
wb.save('./resources/excels/' + filename)
print('保存成功！')